<template>
  <div class="kong">
    <el-dialog
      v-model="cycleVisible"
      width="40%"
      :close-on-click-modal="false"
      :before-close="handleClose"
      center
    >
      <div>
        <el-form ref="rowRef" :rules="rules" :v-model="row" label-width="120px">
          <el-form-item label="计划开始时间" prop="planStartTime">
            <el-date-picker
              v-model="row.planStartTime"
              type="date"
              placeholder="计划开始时间"
            />
          </el-form-item>
          <el-form-item label="计划完成时间" prop="planEndTime">
            <el-date-picker
              v-model="row.planFinishTime"
              type="date"
              placeholder="计划完成时间"
            />
          </el-form-item>
          <el-form-item label="计划规则" prop="planRules">
            <el-select
              :value="row.planRules"
              v-model="row.planRules"
              placeholder="计划规则"
            >
              <el-option
                v-for="item in planRulesList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                default-first-option
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            v-if="row.planRules === 1"
            label="规则选择"
            prop="ruleValues"
          >
            <el-checkbox-group v-model="row.chosenWeeks" :min="1" :max="7">
              <el-checkbox v-for="(day, i) in weeks" :key="day" :label="i + 1">
                {{ day }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>

          <el-form-item
            v-if="row.planRules === 2"
            label="规则选择"
            prop="ruleValues"
          >
            间隔 &nbsp;<el-input-number
              v-model="row.choseIntervals"
              :min="1"
              :max="10"
            />
            天
          </el-form-item>

          <el-form-item
            v-if="row.planRules === 3"
            label="规则选择"
            prop="ruleValues"
          >
            <el-date-picker
              v-model="row.choseDates"
              type="dates"
              align="right"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="指定日期选择"
              @change="changeSpecialDate"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="changeStatus(!cycleVisible)">取 消</el-button>
          <el-button type="primary" @click="submitUpdateIt()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs, onMounted } from 'vue'
import type { cycleRows, rows } from '../scheduleSetting'
import { selectDetail } from '@/constants/commonSelect'
import { getGroupDetail } from '@/api/config'
import { ElMessage, FormRules } from 'element-plus'
import { schedulePlanAdds, schedulePlanQuery } from '@/api/schedulePlan'

const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

const required = (message?: string) => {
  return {
    required: true,
    message: message,
    trigger: 'blur',
  }
}

const handleClose = (done: () => void) => {
  changeStatus(!cycleVisible)
  done()
}

const rules = reactive<FormRules>({})

interface Props {
  cycleVisible?: Boolean
}
const myProps = defineProps<Props>()

const { cycleVisible } = toRefs(myProps)

const emit = defineEmits(['getCycleConfig'])

const changeStatus = (status: boolean) => {
  emit('getCycleConfig', status)
}

// 初始化查询
onMounted(() => {
  getPlanRules()
})

const query = () => {
  schedulePlanQuery(row.scheduleId).then((res: any) => {
    if (res.code === 0 && res.data) {
      var rows = res.data
      row.scheduleId = rows.scheduleId
      row.planStartTime = rows.planStartTime
      row.planFinishTime = rows.planFinishTime
      row.planRules = rows.planRules
      row.ruleValues = rows.ruleValues
      if (row.planRules === 1) {
        row.chosenWeeks = [...row.ruleValues.split(',').map(Number)]
      }

      if (row.planRules === 2) {
        row.choseIntervals = row.ruleValues
      }

      if (row.planRules === 3) {
        row.choseDates = row.ruleValues.split(',')
      }
    }
  })
  return row
}

const changeSpecialDate = () => {
  row.planStartTime = row.choseDates[0]
  row.planFinishTime = row.choseDates[row.choseDates.length - 1]
}

const submitUpdateIt = () => {
  if (row.planRules === 1) {
    row.ruleValues = row.chosenWeeks
    row.ruleValues = row.ruleValues.map(String).join(',')
  }
  if (row.planRules === 2) {
    row.ruleValues = row.choseIntervals
  }
  if (row.planRules === 3) {
    row.ruleValues = row.choseDates.map(String).join(',')
  }
  schedulePlanAdds(row).then((res: any) => {
    if (res.data === true) {
      changeStatus(!cycleVisible)
      initsRow()
      ElMessage({
        type: 'success',
        message: '添加/修改成功',
      })
    }
  })
}

const planRulesList = ref<selectDetail[]>([])

const getPlanRules = async () => {
  getGroupDetail('constgroup_plan_rules').then((res: any) => {
    planRulesList.value = res
  })
}

let row: cycleRows = reactive({
  scheduleId: '0',
  planStartTime: new Date(),
  planFinishTime: new Date(),
  planRules: 1,
  chosenWeeks: [],
  choseIntervals: 1,
  choseDates: [],
  ruleValues: '',
})

const initsRow = () => {
  row.scheduleId = ''
  row.planStartTime = new Date()
  row.planFinishTime = new Date()
  row.planRules = 1
  row.chosenWeeks = []
  row.choseIntervals = 1
  row.choseDates = []
  row.ruleValues = ''
  return row
}

const initsObj = (rows: rows) => {
  row = initsRow()
  row.scheduleId = rows.id
  row = query()
}

defineExpose({
  initsObj,
})
</script>

<style lang="scss" scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
